import showMsg from "../utils/showMsg";

export const sendAi = async (msg, dom) => {
  const res = await fetch("http://localhost:4000/test/kimi", {
    method: "POST", // post 请求
    headers: {
      // 设置请求头
      "content-type": "application/json",
    },
    body: JSON.stringify({
      message: msg,
      userId: Date.now().toString(),
    }), // 设置请求体
  });
  const data = await res.json();
  if (data.status === 200) {
    startSSEConn(data.userId, dom);
  }
}

export const startSSEConn = (userId, dom) => {
  const eventSource = new EventSource(
    `${process.env.VUE_APP_API_BASE_URL}/test/stream?userId=${userId}`
  );

  // 消息
  eventSource.onmessage = (e) => {
    const str = e.data;
    for (const char of str) {
      dom.innerHTML += char;
    }
  };

  // 报错
  eventSource.onerror = (err) => {
      showMsg({
        content: '亲~😘,消息有点回复不过来了,请谅解',
        type: 'info'
      })
  }

  // 连接
  // eventSource.onopen

  // 关闭
  window.addEventListener("beforeunload", () => {
    eventSource.close();
  });
}